<template>
  <view class="page">
    <view class="form-card">
      <view class="form-item">
        <text class="label">昵称</text>
        <input class="input" v-model="form.nickname" placeholder="请输入昵称" />
      </view>

      <view class="form-item">
        <multi-image-uploader 
          :images.sync="avatarList"
          title="头像"
          tip="选择一张图片作为头像"
          :maxCount="1"
          module="user"
          @upload-success="onAvatarUploadSuccess"
        />
      </view>

      <view class="form-item">
        <text class="label">性别</text>
        <view class="gender-row">
          <view 
            v-for="opt in genderOptions" 
            :key="opt.value" 
            :class="['gender-chip', form.gender === opt.value ? 'active' : '']"
            @click="form.gender = opt.value"
          >{{ opt.label }}</view>
        </view>
      </view>

      <view class="form-item">
        <text class="label">手机号</text>
        <input class="input" v-model="form.phone" type="number" placeholder="请输入手机号(可选)" />
      </view>

      <!-- 密码编辑 -->
      <view class="form-item" v-if="showPasswordEdit">
        <!-- 如果不是微信登录用户，显示原密码 -->
        <text class="label" v-if="!isWechatUser">原密码</text>
        <input 
          v-if="!isWechatUser"
          class="input" 
          v-model="form.oldPassword" 
          type="password" 
          placeholder="请输入原密码"
          style="margin-bottom: 16rpx;"
        />

        <!-- 新密码 -->
        <text class="label">{{ isWechatUser ? '设置密码' : '新密码' }}</text>
        <input 
          class="input" 
          v-model="form.newPassword" 
          type="password" 
          :placeholder="isWechatUser ? '请输入密码' : '请输入新密码'"
        />
      </view>

      <!-- 密码编辑按钮 -->
      <view class="form-item" v-if="!showPasswordEdit">
        <button class="btn-edit-password" @click="showPasswordEdit = true">编辑密码</button>
      </view>

      <button class="btn-save" @click="onSubmit" :disabled="saving">{{ saving ? '保存中...' : '保存' }}</button>
    </view>
  </view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { updateUserProfile } from '@/api/user'
import MultiImageUploader from '@/components/MultiImageUploader.vue'
import md5 from '@/utils/md5'

export default {
  components: {
    MultiImageUploader
  },
  data() {
    return {
      form: {
        nickname: '',
        avatar: '',
        gender: 0,
        phone: '',
        oldPassword: '',
        newPassword: ''
      },
      avatarList: [],
      saving: false,
      showPasswordEdit: false,
      isWechatUser: false,  // 是否是微信登录用户
      genderOptions: [
        { label: '未知', value: 0 },
        { label: '男', value: 1 },
        { label: '女', value: 2 }
      ]
    }
  },
  computed: {
    ...mapGetters('user', ['userInfo'])
  },
  onLoad() {
    // 初始化表单
    if (this.userInfo) {
      this.form.nickname = this.userInfo.nickname || ''
      this.form.avatar = this.userInfo.avatar || ''
      this.form.gender = this.userInfo.gender ?? 0
      this.form.phone = this.userInfo.phone || ''
      // 初始化头像列表
      if (this.form.avatar) {
        this.avatarList = [this.form.avatar]
      }
      
      // 检查是否是微信登录用户（密码是 MD5("123456")）
      // MD5("123456") = "25d55ad283aa400af464c76d713c07ad"
      this.isWechatUser = this.userInfo.password === '25d55ad283aa400af464c76d713c07ad'
    }
  },
  methods: {
    ...mapActions('user', ['getUserInfo']),
    onAvatarUploadSuccess(data) {
      // 上传成功后，取第一张图片作为头像
      if (data.newImages && data.newImages.length > 0) {
        this.form.avatar = data.newImages[0].url || data.newImages[0]
      }
    },
    async onSubmit() {
      if (!this.form.nickname || !this.form.nickname.trim()) {
        uni.showToast({ title: '请输入昵称', icon: 'none' })
        return
      }
      if (this.form.phone && !/^\d{5,}$/.test(this.form.phone)) {
        uni.showToast({ title: '手机号格式不正确', icon: 'none' })
        return
      }
      
      // 如果显示了密码编辑，需要验证密码
      if (this.showPasswordEdit) {
        if (!this.form.newPassword || this.form.newPassword.trim().length < 6) {
          uni.showToast({ title: '密码至少6位', icon: 'none' })
          return
        }
        // 非微信用户需要验证原密码
        if (!this.isWechatUser && !this.form.oldPassword) {
          uni.showToast({ title: '请输入原密码', icon: 'none' })
          return
        }
      }
      
      try {
        this.saving = true
        const updateData = {
          nickname: this.form.nickname.trim(),
          avatar: (this.form.avatar || '').trim(),
          gender: Number(this.form.gender) || 0,
          phone: (this.form.phone || '').trim()
        }
        
        // 如果编辑了密码，添加密码字段（需要 MD5 加密）
        if (this.showPasswordEdit && this.form.newPassword) {
          // 微信用户使用默认密码 MD5("123456")
          if (this.isWechatUser) {
            updateData.oldPassword = '25d55ad283aa400af464c76d713c07ad'
          } else {
            // 普通用户需要 MD5 加密原密码
            updateData.oldPassword = md5(this.form.oldPassword.trim())
          }
          // 新密码也需要 MD5 加密
          updateData.newPassword = md5(this.form.newPassword.trim())
        }
        
        await updateUserProfile(updateData)
        // 刷新本地用户信息
        await this.getUserInfo()
        uni.showToast({ title: '保存成功', icon: 'success' })
        setTimeout(() => {
          uni.navigateBack()
        }, 800)
      } catch (error) {
        uni.showToast({ title: (error && error.message) ? error.message : '保存失败', icon: 'none' })
      } finally {
        this.saving = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 24rpx;
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
}

.form-item {
  margin-bottom: 24rpx;
}

.label {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 12rpx;
}

.input {
  width: 100%;
  height: 72rpx;
  border-radius: 12rpx;
  background: #f5f7fa;
  padding: 0 20rpx;
  font-size: 28rpx;
}


.gender-row {
  display: flex;
  gap: 12rpx;
}

.gender-chip {
  padding: 12rpx 20rpx;
  border-radius: 24rpx;
  background: #f5f5f5;
  color: #666;
  font-size: 24rpx;
}

.gender-chip.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.btn-edit-password {
  width: 100%;
  height: 72rpx;
  border-radius: 12rpx;
  background: #f5f7fa;
  color: #667eea;
  font-size: 28rpx;
  font-weight: bold;
  border: 2rpx solid #667eea;
}

.btn-save {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  font-size: 30rpx;
  font-weight: bold;
  border: none;
  margin-top: 8rpx;
}
</style>
